package com.example.demo1.util;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.entity.ContentType;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.Args;
import org.apache.http.util.CharArrayBuffer;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;

/**
 * @Description:
 * @Author Taogang
 * @Date 2017-11-29 19:24
 **/
public class EntityUtils {

	public static String toString(HttpEntity entity, String defaultCharset) throws IOException, ParseException {
		return toString(entity, defaultCharset != null ? Charset.forName(defaultCharset) : null);
	}

	public static String toString(HttpEntity entity, Charset defaultCharset) throws IOException, ParseException {
		Args.notNull(entity, "Entity");
		ContentType contentType = null;

		try {
			contentType = ContentType.get(entity);
		} catch (UnsupportedCharsetException var4) {
			if (defaultCharset == null) {
				throw new UnsupportedEncodingException(var4.getMessage());
			}
		}

		if (contentType != null) {
			if (contentType.getCharset() == null) {
				contentType = contentType.withCharset(defaultCharset);
			}
		} else {
			contentType = ContentType.DEFAULT_TEXT.withCharset(defaultCharset);
		}

		return toString(entity, contentType);
	}

	private static String toString(HttpEntity entity, ContentType contentType) throws IOException {
		InputStream instream = entity.getContent();
		if (instream == null) {
			return null;
		} else {
			try {
				Args.check(entity.getContentLength() <= 2147483647L, "HTTP entity too large to be buffered in memory");
				int capacity = (int)entity.getContentLength();
				if (capacity < 0) {
					capacity = 4096;
				}

				Charset charset = null;
				if (contentType != null) {
					charset = contentType.getCharset();
					if (charset == null) {
						ContentType defaultContentType = ContentType.getByMimeType(contentType.getMimeType());
						charset = defaultContentType != null ? defaultContentType.getCharset() : null;
					}
				}

				if (charset == null) {
					charset = HTTP.DEF_CONTENT_CHARSET;
				}

				Reader reader = new InputStreamReader(instream, charset);
				CharArrayBuffer buffer = new CharArrayBuffer(capacity);
				char[] tmp = new char[1024];

				int l;
				while((l = reader.read(tmp)) != -1) {
					buffer.append(tmp, 0, l);
				}

				String var9 = buffer.toString();
				return var9;
			} finally {
				instream.close();
			}
		}
	}

}
